<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------

namespace think\db\connector;

use PDO;
use think\db\Connection;

/**
 * Sqlsrv数据库驱动
 */
class Sqlsrv extends Connection
{
    // PDO连接参数
    protected $params = [
        PDO::ATTR_CASE              => PDO::CASE_NATURAL,
        PDO::ATTR_ERRMODE           => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_STRINGIFY_FETCHES => false,
    ];
    protected $builder = '\\think\\db\\builder\\Sqlsrv';
    /**
     * 解析pdo连接的dsn信息
     * @access protected
     * @param array $config 连接信息
     * @return string
     */
    protected function parseDsn($config) {
      $dsn = 'sqlsrv:Database='.$config['database'].';Server='.$config['hostname'];
      if (!empty($config['hostport'])) {
        $dsn .= ','.$config['hostport'];
      }
      return $dsn;
    }

    /**
     * 取得数据表的字段信息
     * @access public
     * @param string $tableName
     * @return array
     */
    public function getFields($tableName) {
      $info   = [];
      $table = explode('.', $tableName);  // bar|foo.bar|foo.dbo.bar
      $table = $table[count($table)-1];
      $sql = "SELECT c.ORDINAL_POSITION AS COLUMN_ID, c.COLUMN_NAME, c.DATA_TYPE AS COLUMN_TYPE, c.COLUMN_DEFAULT, ( CASE c.IS_NULLABLE WHEN 'NO' THEN 0 ELSE 1 END ) AS IS_NULLABLE, ( CASE WHEN u.ORDINAL_POSITION > 0 THEN 1 ELSE 0 END ) AS IS_PRIMARY FROM INFORMATION_SCHEMA.TABLES AS t LEFT JOIN INFORMATION_SCHEMA.COLUMNS AS c ON t.TABLE_CATALOG = c.TABLE_CATALOG AND t.TABLE_SCHEMA = c.TABLE_SCHEMA AND t.TABLE_NAME = c.TABLE_NAME LEFT JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS u ON c.TABLE_CATALOG = u.TABLE_CATALOG AND c.TABLE_SCHEMA = u.TABLE_SCHEMA AND c.TABLE_NAME = u.TABLE_NAME AND c.COLUMN_NAME = u.COLUMN_NAME WHERE t.TABLE_TYPE = 'BASE TABLE' AND t.TABLE_NAME = '{$table}' ORDER BY c.ORDINAL_POSITION ASC";
      $eax = $this->getConfig('debug');
      $this->setConfig('debug', 0); // 强制不记录日志
      $pdo = $this->query($sql, [], false, true);
      $this->setConfig('debug', $eax);

      $result = $pdo->fetchAll(PDO::FETCH_ASSOC);
      if ($result) {
        foreach($result as $key => $val) {
          $info[$val['COLUMN_NAME']] = [
            'name' => $val['COLUMN_NAME'],
            'type' => $val['COLUMN_TYPE'],
            'notnull' => $val['IS_NULLABLE'],
            'default' => $val['COLUMN_DEFAULT'],
            'primary' => $val['IS_PRIMARY'],
            'autoinc' => false, // ???标识/标识种子/标识增量
          ];
        }
      }
      return $this->fieldCase($info);
    }

    /**
     * 取得数据表的字段信息
     * @access public
     * @param string $dbName
     * @return array
     */
    public function getTables($dbName = '') {
      $sql = "SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE'";
      $pdo = $this->query($sql, [], false, true);
      $result = $pdo->fetchAll(PDO::FETCH_ASSOC);
      $info = [];
      foreach($result as $key => $val) {
        $info[$key] = current($val);
      }
      return $info;
    }

    /**
     * SQL性能分析
     * @access protected
     * @param string $sql
     * @return array
     */
    protected function getExplain($sql) {
      return [];
    }
}
